package Thread;

/**
 * 自己实现的阻塞队列
 *
 * 此处不考虑反泛型参数,只是基于String进行存储
 */

public class MyBlockingQueue {
    //
    private String[] data = null;
    private volatile int head = 0;
    private volatile int tail = 0;
    private volatile int size = 0;


    //锁对象
    private Object locker = new Object();

    public MyBlockingQueue (int capacity){
        data = new String[capacity];//这里的 capacity 是分配的内存空间
    }

    //往阻塞队列中存入任务
    public void put(String s) throws InterruptedException {
        synchronized (this){
            while(size == data.length){
                //队列满了,进行等待
                this.wait();
            }
            data[tail] = s;
            tail ++;
            if(tail >= data.length){
                tail = 0;
            }
            size ++;

            this.notify();
        }
    }

    //从阻塞队列中取出任务
    public String take() throws InterruptedException {
        String ret = "";
        synchronized (this){
            while(size == 0){
                //队列为空,等待直到队列中有任务的时候被唤醒
                this.wait();
            }
            ret = data[head];
            head ++;
            if(head >= data.length){
                head = 0;
            }
            size --;

            this.notify();
        }
        return ret;
    }
}
